package picture

import (
	"chain_bridge_service/configs"
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func NewModel() *Picture {
	return new(Picture)
}

func (s *Picture) Create(db *mongo.Client) error {
	cfgs := configs.Get().Mongodb
	pictureClient := db.Database(cfgs.Config.Name).Collection("picture")
	_, err := pictureClient.InsertOne(context.TODO(), s)
	return err
}

func (s *Picture) Update(db *mongo.Client) error {
	cfgs := configs.Get().Mongodb
	pictureClient := db.Database(cfgs.Config.Name).Collection("picture")
	objId, _ := primitive.ObjectIDFromHex(s.Id)
	filter := bson.M{"_id": objId}
	update := bson.M{"$set": bson.M{
		"pictureUrl": s.PictureUrl,
		"skipUrl":    s.SkipUrl,
		"fileName":   s.FileName,
	}}
	_, err := pictureClient.UpdateOne(context.TODO(), filter, update)
	return err
}

func (s *Picture) List(db *mongo.Client, pageIndex uint, pageSize uint) ([]Picture, error) {
	var pictureList []Picture
	cfgs := configs.Get().Mongodb
	pictureClient := db.Database(cfgs.Config.Name).Collection("picture")

	skip := int64((pageIndex - 1) * pageSize)
	findOptions := options.Find()
	findOptions.SetSort(bson.D{{"_id", -1}})
	findOptions.SetSkip(skip)
	findOptions.SetLimit(int64(pageSize))

	find, err := pictureClient.Find(context.TODO(), bson.D{}, findOptions)
	if err != nil {
		return nil, err
	}
	err = find.All(context.TODO(), &pictureList)
	return pictureList, err
}

func (s *Picture) Delete(db *mongo.Client) error {
	cfgs := configs.Get().Mongodb
	pictureClient := db.Database(cfgs.Config.Name).Collection("picture")
	objId, _ := primitive.ObjectIDFromHex(s.Id)
	_, err := pictureClient.DeleteOne(context.TODO(), bson.D{{"_id", objId}})
	return err
}

func (s *Picture) FindOne(db *mongo.Client) (Picture, error) {
	var picture Picture
	cfgs := configs.Get().Mongodb
	pictureClient := db.Database(cfgs.Config.Name).Collection("picture")
	objId, _ := primitive.ObjectIDFromHex(s.Id)
	err := pictureClient.FindOne(context.TODO(), bson.D{{"_id", objId}}).Decode(&picture)
	return picture, err
}

func (s *Picture) Count(db *mongo.Client) (int64, error) {

	cfgs := configs.Get().Mongodb
	pictureClient := db.Database(cfgs.Config.Name).Collection("picture")
	documents, err := pictureClient.CountDocuments(context.TODO(), bson.D{})
	return documents, err
}
